package com.utils.http;

import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.util.Arrays;

public class HttpUtil {
    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        try {
            //请求链接
            HttpPost httpPost = new HttpPost("http://21.117.67.59:11014/file/upload");
            //设置请求头
            httpPost.setHeader("head1", "jiami");
            //请求文件
            File file = new File("C:\\Users\\dbgs\\Pictures\\啊.jpg");
            //构建文件
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            multipartEntityBuilder.addBinaryBody("file", file, ContentType.create("multipart/form-data", Consts.UTF_8), file.getName());
            HttpEntity build = multipartEntityBuilder.build();
            //设置文件
            httpPost.setEntity(build);

            log.info("executing request " + httpPost.getRequestLine());
            HttpResponse response = httpclient.execute(httpPost);
            httpPost.releaseConnection();
            //响应体
            HttpEntity resEntity = response.getEntity();
            //响应头
            Header[] allHeaders = response.getAllHeaders();

            log.info("----------------------------------------");
            log.info(Arrays.toString(allHeaders));
            log.info(response.getStatusLine().toString());
            if (resEntity != null) {
                log.info("Response content length: " + resEntity.getContentLength());
            }
            EntityUtils.consume(resEntity);
        } catch (Exception e) {
            log.error("httpPost 失败");
        } finally {
            try {
                httpclient.close();
            } catch (Exception ignore) {
                log.error("httpclient 关闭异常");
            }
        }
    }



    static class log {
        static void info(String s) {
            System.out.println(s);
        }

        static void error(String s) {
            System.out.println(s);
        }
    }
}
